# -*- coding: utf-8 -*-
import threading
from zc_core.client.mongo_client import Mongo
from zc_core.model.items import ItemData, ItemPoolData, Spu, OrderItem


class BrandHelper(object):
    _instance_lock = threading.Lock()
    _biz_inited = False

    def __new__(cls, *args, **kwargs):
        if not hasattr(BrandHelper, "_instance"):
            with BrandHelper._instance_lock:
                if not hasattr(BrandHelper, "_instance"):
                    BrandHelper._instance = object.__new__(cls)
        return BrandHelper._instance

    def __init__(self):
        if not self._biz_inited:
            self._biz_inited = True
            self.mongo = Mongo()
            coll = self.mongo.get_collection('brand_pool')
            self.id_dict = dict()
            self.name_dict = dict()
            self.code_dict = dict()
            if coll:
                pool = coll.find()
                if pool:
                    for brand in pool:
                        self.id_dict[brand.get('_id')] = brand
                        self.name_dict[brand.get('name')] = brand
                        code = brand.get('code', '')
                        if code:
                            self.code_dict[brand.get('code')] = brand

    def fill(self, item):
        # 商品数据、商品池数据、订单明细
        if isinstance(item, ItemData) or isinstance(item, Spu) \
                or isinstance(item, ItemPoolData) or isinstance(item, OrderItem):
            sp_id = item.get('brandId')
            sp_name = item.get('brandName')
            sp_code = item.get('brandCode', '')
            if sp_id and sp_id in self.id_dict:
                sp = self.id_dict.get(sp_id)
                item['brandName'] = sp.get('name')
                if self.code_dict and sp.get('code', ''):
                    item['brandCode'] = sp.get('code', '')
            elif sp_name and sp_name in self.name_dict:
                sp = self.name_dict.get(sp_name)
                item['brandId'] = sp.get('_id')
                if self.code_dict and sp.get('code', ''):
                    item['brandCode'] = sp.get('code', '')
            elif sp_code and self.code_dict and sp_code in self.code_dict:
                sp = self.code_dict.get(item.get('brandName'))
                item['brandId'] = sp.get('_id')
                item['brandName'] = sp.get('name')

        return item

    # 关闭链接
    def close(self):
        self.mongo.close()
